package dq.study.concurrent.until;

import java.util.concurrent.CountDownLatch;
import java.util.concurrent.Executor;
import java.util.concurrent.Executors;

/**
 * 利用CountdownLatch实现多线程的协同工作
 *
 * <p>
 * <i>业务细节</i>
 * 将一个任务分成几块，分别用一个线程执行一块，利用countdownlatch全部执行完成后，再回到主线程汇总
 * <p/>
 *
 * @author dongqun
 * @version 1.0.0
 * @since 2021/08/31 10:34:00
 */
public class CountDownLatchTest2 {
    public static void main(String[] args) throws InterruptedException {
        CountDownLatch done = new CountDownLatch(10);
        Executor executor = Executors.newCachedThreadPool();
        for (int i = 0; i < 10; i++) {
            executor.execute(new Worker(done));
        }
        done.await();
        System.out.println("all work done.");
    }

    static class Worker implements Runnable {
        private final CountDownLatch done_Signal;

        Worker(CountDownLatch doneSignal) {
            this.done_Signal = doneSignal;
        }

        @Override
        public void run() {
            try {
                doWorker();
            } catch (Exception e) {
                e.printStackTrace();
            } finally {
                done_Signal.countDown();
            }

        }

        private void doWorker() {
            System.out.println("worker thread do something");
        }
    }
}
